<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/8/2
 * Time: 17:39
 */

namespace app\home\controller;

use app\common\model\User as umodel;
use think\Db;

class Set extends Common
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 设置中心
     */
    public function index()
    {
        $this->templateTitle("设置中心");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $userinfo['userlevel'] = umodel::thatlevel($userinfo['levelid']);
        $this->assign('userinfo', $userinfo);
        return $this->fetch("index");
    }


    /*SCB 复制的上面推广收益 zhuang */
    /*SCB 新增SCB历史 xuanfeng   */
    public function bot()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return['msg']);
            $this->redirect('User/index');
        }
        /*读取前五条*/
        $list = db('mybot')->where("uid='" . $uid . "'")->order('id desc')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch("bot");
    }

    /*ajax 加载推广收益*/
    public function ajaxbot()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 10;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $map['uid'] = session("user_id");
        $list = \db('mybot')->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }


    /**
     * 共享豆记录
     */
    public function finance()
    {
        $this->templateTitle("共享豆记录");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return["msg"]);
            $this->redirect("User/index");
        }
        /*读取前五条*/
        $list = db('points')->where("uid='" . $uid . "'")->order('id desc')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch("finance");
    }

    public function ajaxmorefinance()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 10;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $map['uid'] = session("user_id");
        $list = db('points')->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /**
     * 共享豆转出
     */
    public function financeOut()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        return $this->fetch("finance_out");
    }

//    SCB转出  复制的上面共享豆转出
    public function botOut()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        return $this->fetch("bot_out");
    }

    //    发布订单  复制的上面共享豆转出
    public function orderPublish()
    {
        $uid = session("user_id");
        if(request()->isAjax()){
            $num = intval(input('num'));
            $price = input('price');
            if($num<=0){
                $this->ajaxError('求购数量需为正整数');
            }
            $qiugou = intval(config('setting.qiugou'));
            if($num<$qiugou){
                $this->ajaxError('求购数量'.$qiugou.'起购');
            }
            if($price<0){
                $this->ajaxError('求购单价不合法');
            }
            $data = [
                'user_id'=>$uid,
                'num'=>$num,
                'price'=>$price,
                'create_time'=>now_datetime(),
                'status'=>1
            ];
            $res = \db('trade_order')->insert($data);
            if(empty($res)){
                $this->ajaxError('发布失败');
            }else{
                $this->ajaxSuccess('发布成功');
            }
        }
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $count = \app\common\model\User::getChargeCount($uid);
        if(!$count>=2){

            $this->assign('tips', "请绑定两个以上（包含两个）的收款码");
            $this->assign("redirect_url", \url('User/add_bank'));
            return $this->fetch('alert_window');
        }
        //查看是否已经实名认证
        $userinfo = userallinfo($uid);
        $is_verify = 0;
        if ($userinfo['selfcard'] <> '' && $userinfo['realname'] <> '') {
            $is_verify = 1;
        }
        if(!$is_verify){
            $this->assign('tips', "请先去实名认证");
            $this->assign("redirect_url", \url('User/certification'));
            return $this->fetch('alert_window');
        }
        return $this->fetch("order_publish");
    }

    /*执行转增并扣除对应共享豆--xuanfeng--20190620*/
    public function transpoint()
    {
        $returncode = \app\common\model\User::transpoint($_POST);
        echo json_encode($returncode);
    }

    /*合约收益  xuanfeng 20190614*/
    public function earnings()
    {
        //1 4 3 5 7 8
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $userlevel = \db('userlevel')->where("id", $userinfo['levelid'])->value("title");
        $userinfo["userlevel"] = empty($userlevel) ? "暂无等级" : $userlevel;
        $this->assign('userinfo', $userinfo);

        /*读取前五条*/
        $list = \db('orderearn')->where("uid='" . $uid . "' and `status`=2")->order('sendtime desc, id desc')->limit(10)->select();
        $this->assign('list', $list);

        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return["msg"]);
            $this->redirect('User/index');
        }
        return $this->fetch("earnings");
    }

    /*ajax 加载收益记录*/
    public function ajaxmoreearn()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 10;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $list = \db('orderearn')->where("uid='" . session("user_id") . "'  and `status`=2")->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['sendtime'] = date('Y-m-d H:i:s', $v['sendtime']);
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /*推广收益 xuanfeng 20190614*/
    public function popularize()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return['msg']);
            $this->redirect('User/index');
        }
        /*读取前五条*/
        $list = db('pushslist')->where("uid='" . $uid . "'")->order('id desc')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch("popularize");
    }

    /*累计收益 复制的上面推广收益 zhuang */
    public function cumulative()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return['msg']);
            $this->redirect('User/index');
        }
        /*读取前五条*/
        $list = db('pushslist')->where("uid='" . $uid . "'")->order('id desc')->limit(10)->select();
        $this->assign('list', $list);
        return $this->fetch("cumulative");
    }

    /*ajax 加载推广收益*/
    public function ajaxpopularize()
    {
        $page = $_POST['page'];/*当前是第几页*/
        $page_num = 10;/*每次读取5条*/
        $limit_first = ($page - 1) * $page_num;
        $limit_end = $page_num;

        $map['uid'] = session("user_id");
        $list = \db('pushslist')->where($map)->order('id desc')->limit($limit_first, $limit_end)->select();
        if (!empty($list)) {
            $ary = $list;
            foreach ($ary as $k => $v) {
                $ary[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
            }
        } else {
            $ary = [];
        }
        echo json_encode($ary);
    }

    /*推广收益-转增  xuanfeng 20190614*/
    public function popularizecon()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        /*如果没有实名认证，是不允许进入这个页面的*/
        $set_return = \app\common\model\User::activestatus($userinfo);
        if ($set_return['msg'] != 'ok') {
            session("tips", $set_return['msg']);
            $this->redirect('User/index');
        }
        /*查一下最便宜的产品*/
        $product_min = \db('goods')->where("isshow=1")->order('price1 asc')->find();
        $this->assign('product_min', $product_min);
        return $this->fetch("popularizecon");
    }

    /*----推广收益出售---xuanfeng --20190627---*/
    public function sale_create_order()
    {
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        if (empty($uid)) {
            $ary = array('s' => 1, 'msg' => '请先登录！');
            echo json_encode($ary);
        }
        $data['num'] = trim($_POST['num']);
        $data['pwd'] = trim($_POST['pwd']);
        if (empty($data['num'])) {
            $ary = array('s' => 2, 'msg' => '出售数量填写错误，请检查！');
            echo json_encode($ary);
            exit;
        }
        /*检测产品是否有这个价位的，当然要先检测一下最低出售数量是多少！*/
        /*查一下最便宜的产品*/
        //$product_min = db('goods')->where("isshow=1")->order('price1 asc')->value('price1');
        $product_min = config('setting.recommendprice');
        if ($data['num'] < $product_min) {
            $ary = array('s' => 2, 'msg' => '出售失败，资产出售最低金额不小于:' . $product_min . '！');
            echo json_encode($ary);
            exit;
        }
        $product_max = db('goods')->where("isshow=1")->order('price2 desc')->value('price2');
        if ($data['num'] > $product_max) {
            $ary = array('s' => 2, 'msg' => '最大可出售资产额度为:' . $product_max . '！');
            echo json_encode($ary);
            exit;
        }
        if ($data['num'] > $userinfo['pushs']) {
            $ary = array('s' => 2, 'msg' => '余额不足！您的资产额度为:' . $userinfo['pushs'] . '！');
            echo json_encode($ary);
            exit;
        }

        if (empty($data['pwd'])) {
            $ary = array('s' => 3, 'msg' => '请填写交易密码！');
            echo json_encode($ary);
            exit;
        }
        /*每日出售次数限制，可以进行后台配置！！！*/


        if (md5(md5($data['pwd'])) == $userinfo['sepasswd']) {
            //执行出售，并获取对应的产品信息，添加出售订单，如果成功，那先加一个资产记录，再减掉用户的资产
            $productlist = db('goods')->where("isshow=1")->order("price2 desc")->select();
            $product_con = [];
            foreach ($productlist as $v) {
                if ($data['num'] > $v['price1'] && $data['num'] <= $v['price2']) {
                    $product_con = $v;
                    break;
                }
            }
            if (empty($product_con)) {
                $ary = array('s' => 10, 'msg' => '该数量额度已售光，请重新填写出售数量！');
                echo json_encode($ary);
                exit;
            }
            //查看共享豆数量是否足够
            if ($product_con['point_end'] > $userinfo['integral']) {
                $ary = array('s' => 2, 'msg' => '本次出售需要共享豆' . $product_con['point_end'] . '个，你的共享豆不足！');
                echo json_encode($ary);
                exit;
            }
            //开始执行插入order表的sql语句，就卖给自己好了

            //先把会员共享豆扣了，然后添加新的订单
            \db('user')->where("id='" . $userinfo['id'] . "'")->setDec('integral', $product_con['point_end']);
            //再把会员的共享豆历史加上
            points_his($userinfo['id'], 2, $product_con['point_end'], 0, '出售[推广收益]扣除');
            //先减掉团队收益
            \db('User')->where("id='" . $userinfo['id'] . "'")->setDec('pushs', $data['num']);
            //再添加团队收益记录
            pushs_his($userinfo['id'], 2, $data['num'], 0, '推广收益出售');


            $data_sure['buyuid'] = $userinfo['id'];
            $data_sure['buyuidatc'] = $product_con['atcnum'];
            $data_sure['caifen'] = $product_con['point_end'];
            $data_sure['productid'] = $product_con['id'];
            $data_sure['title'] = $product_con['title'] . '(出售推广收益)';
            $data_sure['price'] = $data['num'];
            //$data_sure['daynum'] = $product_con['daynum'];
            $data_sure['daynum'] = 0;
            //$data_sure['earnpercent'] = $product_con['daypercent'];
            $data_sure['earnpercent'] = 0;
            //一共能赚多少钱，本金加赚的钱有多少
            //$countprofit = countprofit($data_sure['price'], $data_sure['daynum'], $data_sure['earnpercent']);
            $data_sure['dayaddprice'] = 0;
            //$data_sure['dayaddprice'] = $countprofit['profitall'];

            $data_sure['basicprice'] = $data_sure['price'];
            //$data_sure['basicprice'] = $countprofit['profit_and_day'];

            $data_sure['ctime'] = time();
            $data_sure['peiduistatus'] = 1;
            $data_sure['peiduiuid'] = 0;
            $data_sure['peiduitime'] = 0;
            $data_sure['peiduiid'] = 0;
            $data_sure['paystatus'] = 0;
            $data_sure['paytime'] = time();
            $data_sure['payimg'] = '';
            // $cansaletime = ($data_sure['ctime'] + 86400 * $product_con['daynum']);
            // $cansaletimedate = date('Y-m-d', $cansaletime);
            // $data_sure['cansaletime'] = strtotime($cansaletimedate);
            $now_day_dates = date('Y-m-d');
            $data_sure['thatdatetime'] = strtotime($now_day_dates);
            $data_sure['cansaletime'] = $data_sure['thatdatetime'];
            $data_sure['paytype'] = '';
            $data_sure['xs'] = 2;
            $insertid = db(config('db_order_table'))->insertGetId($data_sure);

            if ($insertid) {
                /*for ($i = 1; $i <= $product_con['daynum']; $i++) {
                    $data_detail['orderid'] = $insertid;
                    $data_detail['uid'] = $userinfo['id'];
                    $data_detail['earnmoney'] = $countprofit['profitday'];
                    $detail_time = ($data_sure['thatdatetime'] + 86400 * $i);
                    $data_detail['dotime'] = date('Ymd', $detail_time);
                    $data_detail['status'] = 1;
                    $data_detail['ctime'] = time();
                    \db('orderearn')->insert($data_detail);
                }*/
                $ary = array('s' => 10, 'msg' => '售出成功！');
                echo json_encode($ary);
                exit;
            } else {
                $ary = array('s' => 4, 'msg' => '系统繁忙，请稍后再试！');
                echo json_encode($ary);
                exit;
            }
        } else {
            $ary = array('s' => 5, 'msg' => '密码错误，请检查输入！');
            echo json_encode($ary);
            exit;
        }
    }

    //首页加一个团队奖兑换
    public function transeo()
    {
        $this->templateTitle("团队奖兑换");
        $uid = session("user_id");
        $userinfo = userallinfo($uid);
        $this->assign('userinfo', $userinfo);
        return $this->fetch();
    }

}
